package cn.autoOffice.controller;

import cn.autoOffice.bean.pojo.Discuss;
import cn.autoOffice.bean.pojo.DocumentManagement;
import cn.autoOffice.common.utils.Result;
import cn.autoOffice.service.DocumentManagementService;
import cn.autoOffice.service.RedisService;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.HashSet;
import java.util.List;

import static cn.autoOffice.common.utils.ResultCodeEnum.SYS_FILE_NOT_EMPTY_ERROR;

/**
 * @author 金健伟
 * @DATE 2023/3/28 16:25
 * 功能说明：
 */

@RestController
@RequestMapping("/file")
@CrossOrigin
public class FileUpAndDownController {

    @Autowired
    @Resource
    private DocumentManagementService documentManagementService;

    @Autowired
    private RedisService redisService;

    @GetMapping("/fileAll")
    // @RequiresPermissions("discuss:select")
    public Result getDocumentAll( @RequestParam("currentPage") Integer currentPage,
                                  @RequestParam("pageSize") Integer pageSize){
        PageInfo pageInfo;
        List<DocumentManagement> discussTitle;
        Integer countFile = documentManagementService.countFile();
        String fileCount = redisService.getValue("allFile" + currentPage);
        if (fileCount != null){
            discussTitle = JSONObject.parseArray(fileCount,DocumentManagement.class);
            pageInfo = new PageInfo(discussTitle);
            pageInfo.setTotal(countFile);
        } else {
            PageHelper.startPage(currentPage,pageSize);
            discussTitle = documentManagementService.getDocumentAll();
            pageInfo = new PageInfo<>(discussTitle);
            redisService.putValue("allFile" + currentPage, discussTitle, 60);
            redisService.putValue("allFileCount",pageInfo.getTotal(),60);
        }

        return Result.success(pageInfo);
    }

    @PostMapping("/upload")
    // @RequiresPermissions("discuss:update")
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.failure(SYS_FILE_NOT_EMPTY_ERROR);
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        String type = FileUtil.extName(fileName);
        long size = file.getSize();
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID = uuid + StrUtil.DOT + type;
        File uploadFile = new File("D:\\vueDemo\\"+fileName);

        if(!uploadFile.getParentFile().exists()){
            uploadFile.getParentFile().mkdirs();
        }
        try {
            // 保存文件
            file.transferTo(uploadFile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 获取文件的后缀名
        // String suffixName = fileName.substring(fileName.lastIndexOf("."));

        // 上传后的路径
        // String filePath = "D:\\vueDemo\\";
        // // String filePath = System.getProperty("user.dir") + "cn/autoOffice/file";
        // // 构建上传路径
        // File dest = new File(filePath + fileName);
        //
        // ;
        //
        // // 检测是否存在目录
        // if (!dest.getParentFile().exists()) {
        //     dest.getParentFile().mkdirs();
        // }
        //
        // try {
        //     // 保存文件
        //     file.transferTo(dest);
        // } catch (IllegalStateException e) {
        //     e.printStackTrace();
        // } catch (IOException e) {
        //     e.printStackTrace();
        // }

        DocumentManagement document = new DocumentManagement();
        document.setEmpId(1);
        document.setDocumentName(fileName);
        String path = uploadFile.getAbsolutePath();
        document.setDocumentAddress(path.substring(0,path.lastIndexOf(fileName)));

        Integer integer = documentManagementService.addDocument(document);
        if (integer > 0){
            return Result.success(uploadFile);
        } else {
            return Result.failure();
        }
    }

    @GetMapping("/down")
    // @RequiresPermissions("discuss:update")
    public void down(HttpServletResponse response ,
                       @RequestParam("documentName") String documentName) throws IOException {
        DocumentManagement document = documentManagementService.getDocument(documentName);
        String fileName = document.getDocumentName();
        if (fileName != null) {
            String realPath = "D:\\vueDemo";
            File file = new File(realPath, fileName);
            ServletOutputStream os = response.getOutputStream();
            if (file.exists()) {
                // 设置强制下载不打开
                response.setContentType("application/force-download");
                response.setHeader("Content-type", "application-download");
                // response.setContentType("application/octet-stream");
                //设置文件名
                response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

            }
            os.write(FileUtil.readBytes(file));
            os.flush();
            os.close();
        }
    }
}
